<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/29 0029
 * Time: 17:25
 */

namespace app\index\controller;
use app\index\model\User;
use think\Controller;
use think\Loader;

class Set extends Controller
{
	/**
	 * 基本设置-我的资料
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function index(){
		$user = User::get(session('user_id'));
		$this->assign('user',$user);
		$this->assign('title','基本设置');
		return $this->fetch();
	}

	/**
	 * 编辑用户的基本信息方法
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function editUser(){
		$post = input('post.');
		$res = User::where('email',$post['email'])->find();
		if ($res && $res->user_id != session('user_id')){
			$this->error('该邮箱已被注册');
		}
		$res = User::where('user_id',session('user_id'))
			->update($post);
		if ($res){
			$this->success('更新成功');
		}else{
			$this->error('更新失败，请稍后再试');
		}
	}

	/**
	 * 编辑用户密码方法
	 */
	public function editPass(){
		$pass = input('post.');
		$validate = Loader::validate('CheckReg');
		if(!$validate->scene('pass')->check($pass)){
			$this->error($validate->getError());
		}
		$res = User::where('user_id',session('user_id'))
			->update(['password'=>md5($pass['password'])]);
		if ($res){
			$this->success('更新成功');
		}else{
			$this->error('更新失败，请稍后再试');
		}
	}

	/**
	 * 上传头像方法
	 */
	public function upload(){
		$file = request()->file('file');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if($file){
			$info = $file->move(ROOT_PATH . 'public/static' . DS . 'uploads');
			if($info){
				$face = 'uploads/'.date('Ymd').'/'.$info->getFilename();
				$user = new User();
				$res = $user->where('user_id', session('user_id'))
					->update(['face'=>$face]);
				session('face',$face);
				$this->error('上传成功');
			}else{
				// 上传失败获取错误信息
				$this->error('上传失败');
			}
		}
	}
}